<?php
###########################################################################
#  Copyright (C) 2006-2007 Glyphix, Inc. <briz@glyphix.com>               #
#                                                                         #
#  Permission is hereby granted, free of charge, to any person obtaining  #
#  a copy of this software and associated documentation files (the        #
#  "Software"), to deal in the Software without restriction, including    #
#  without limitation the rights to use, copy, modify, merge, publish,    #
#  distribute, sublicense, and/or sell copies of the Software, and to     #
#  permit persons to whom the Software is furnished to do so, subject to  #
#  the following conditions:                                              #
#                                                                         #
#  The above copyright notice and this permission notice shall be         #
#  included in all copies or substantial portions of the Software.        #
#                                                                         #
#  Except as contained in this notice, the name(s) of the above           #
#  copyright holders shall not be used in advertising or otherwise to     #
#  promote the sale, use or other dealings in this Software without       #
#  prior written authorization.                                           #
#                                                                         #
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,        #
#  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF     #
#  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. #
#  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR      #
#  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,  #
#  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR  #
#  OTHER DEALINGS IN THE SOFTWARE.                                        #
###########################################################################

/**
 * GXUserXML
 *
 * User management using an XML database. Designed to work tightly with GXPage.
 * @author		Brad Brizendine <briz@glyphix.com>
 * @link		http://www.glyphix.com/
 * @license		http://opensource.org/licenses/bsd-license.php BSD License
 * @version		1.0
 * @package		GXPage
 * @subpackage	Modules
 * @copyright	Copyright 2006 - 2007, Glyphix, Inc.
 * @uses		GXModule
 */

class GXUserXML extends GXModule {

	// the member's cookie name
	private $cookieName = 'adminid';
	// this member's id
	private $adminid;

	// Holds the xml user database
	private static $UserDB;

	function __construct( $config = null ){
		parent::__construct();
		$this->GXCookie = GXCookie::getInstance();

		$path = realpath( $this->GXPage->Layout->FS->Root .$config->exec->xpath('Source',0)->nodeValue );
		if( !$path ){
			trigger_error( 'Missing GXUserXML database', E_USER_ERROR );
			return false;
		}
		// load the user xml file
		self::$UserDB = new GXDOM($path);

		// if no session, check the cookie
		if( !$this->adminid = $this->getUserID() ){
			trigger_error( 'Admin User is not authenticated', E_USER_WARNING );
			$this->GXCookie->delete( $this->cookieName );
			unset($this->adminid);
		}

		return true;
	}

	/**
	 * getUserID
	 * Pulls the admin username from the cookie.
	 * @return string username or false on failure
	 */
	public function getUserID(){
		if( !isset($this->adminid) || !$this->adminid ){
			$this->adminid = $this->GXPage->Params->{$this->cookieName};
		}
		return $this->adminid;
	}

	/**
	 * getUser
	 * @param string $username
	 * @param string $password
	 * @param string "login" or "lookup"
	 * @return object SimpleXML record or false on failure
	 */
	public function getUser( $username = null, $password = null, $purpose = 'login' ){
		$user = null;
		// if we're logging in, need both username and password
		if( $purpose == 'login' && (!$username || !$password) ){
			trigger_error( 'Missing username or password', E_USER_ERROR );
			return false;
		}
		// if it's lookup, need username
		if( $purpose == 'lookup' && (!$username) ){
			trigger_error( 'Missing username', E_USER_ERROR );
			return false;
		}

		// build the xpath
		if( $purpose == 'login' ){
			$xpath = '//User[ Username="' .$username .'" and Password="' .$password .'" ]';
		}else{
			$xpath = '//User[ Username="' .$username .'" ]';
		}

		// do the search
		if( !($user = self::$UserDB->exec->xpath($xpath,0,GXDOM::AS_SIMPLEXML)) ){
			trigger_error( 'Can\'t find a user with that username and/or password', E_USER_ERROR );
			return false;
		}

		// get rid of sensitive info
		unset($user->Password);

		return $user;
	}

	public function showUser(){
		$username = $this->getUserID();
		return $this->getUser( $username, null, 'lookup' );
	}

	public function login( $username = null, $password = null ){
		if( !$username || !$password ){
			trigger_error( 'Missing login info', E_USER_ERROR );
			return false;
		}

		// search for the username/password
		if( !($user = $this->getUser($username,$password,'login')) ){
			trigger_error( 'We cannot locate an account with that information.', E_USER_NOTICE );
			return false;
		}

		// store the username in a cookie
		$this->GXCookie->set( $this->cookieName, strval($user->Username) );
		trigger_error( 'Stored ' .$user->Username .' in ' .$this->cookieName, E_USER_WARNING );

		trigger_error( 'You have successfully signed in as ' .strval($user->FirstName) .' ' .strval($user->LastName) .'.', E_USER_NOTICE );
		return true;
	}

	public function logout(){
		$this->GXCookie->delete( $this->cookieName );
		trigger_error( 'You have successfully signed out.', E_USER_NOTICE );
		return true;
	}

	public function getRoles(){
		if( !$user = $this->getUser() ){
			trigger_error( 'Unable to get User...no session', E_USER_ERROR );
			return false;
		}
		return $user->Auth;
	}

}

?>